package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.AbstractScheduledService;
import com.google.common.util.concurrent.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 结合外部监控和重启
 *
 * @author yangyunjiao
 */
@Slf4j
public class ResilientScheduledServiceManager {

    private AbstractScheduledService service;
    private int count = 0;



    public void startService() {
        service = new ExceptionSchedulerService();
        service.addListener(new Service.Listener() {
            @Override
            public void failed(Service.State from, Throwable failure) {

                log.error("服务失败", failure);

                if (count < 3) {
                    // 延迟后重启服务
                    scheduleRestart();
                    count++;
                }
            }
        }, Executors.newSingleThreadExecutor());

        service.startAsync();
    }

    private void scheduleRestart() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(() -> {
            log.info("尝试重启服务");

            startService();
        }, 1, TimeUnit.SECONDS);
    }



    public static void main(String[] args) throws InterruptedException, TimeoutException {
        ResilientScheduledServiceManager manager = new ResilientScheduledServiceManager();
        manager.startService();
        TimeUnit.SECONDS.sleep(7);

    }
}
